package com.core.image.utils;
import com.core.image.tcp.ConnectorHandler;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * describe:
 *
 * @author 库琦
 * @date 2020/02/09/15:02
 */
public class AudioRoom {
    private final String roomCode;
    private volatile ConnectorHandler handler1;
    private volatile ConnectorHandler handler2;
    public AudioRoom(){
        this.roomCode = getRandString(5);
    }

    public String getRoomCode(){
        return roomCode;
    }

    public ConnectorHandler[] getConnectors(){
        List<ConnectorHandler> handlers = new ArrayList<>(2);
        if (handler1 != null){
            handlers.add(handler1);
        }
        if (handler2 != null){
            handlers.add(handler2);
        }
        return handlers.toArray(new ConnectorHandler[0]);
    }
    public ConnectorHandler getTheOtherHandler(ConnectorHandler handler) {
        return (handler2 == handler || handler1 == null)? handler2:handler1;
    }

    public synchronized boolean isEnable(){
        return handler1 != null && handler2 != null;
    }
    public synchronized boolean enterRoom(ConnectorHandler handler){
        if (handler1 == null){
            handler1 = handler;
        }else if (handler2 == null){
            return false;
        }
        return true;
    }
    /**
     * 退出房间
     *
     * @return 退出后如果还有一人剩余则返回剩余的人
     */
    public synchronized ConnectorHandler exitRoom(ConnectorHandler handler) {
        if (handler1 == handler) {
            handler1 = null;
        } else if (handler2 == handler) {
            handler2 = null;
        }
        return handler1 == null ? handler2 : handler1;
    }


    private static String getRandString(final int length) {
        final String str = "123456";
        final Random random = new Random();
        final StringBuilder sb = new StringBuilder();
        for (int i =0; i < length;i++){
            int number = random.nextInt(str.length());
            sb.append(sb.charAt(number));
        }
        return sb.toString();
    }

}
